import axios from 'axios'
import utils from '@/utils'
import Qs from 'qs'

axios.defaults.baseURL = process.env.WAPI
// global encode params
axios.defaults.paramsSerializer = (params) => {
  return Qs.stringify(params, {arrayFormat: 'brackets'})
}

export default {
  async get (url, params, opt) {
    let startTime = new Date().getTime()
    let welikeToken = utils.cookie.get('welikeToken') || ''
    if (welikeToken) {
      params = Object.assign({}, {
      }, params)
    } else {
      params = Object.assign({}, {
        source: `web`
      }, params)
    }
    let { data } = await axios.get(url, { params }, { withCredentials: true }).catch((error) => {
      return error.response
    })
    let endTime = new Date().getTime()

    if (endTime - startTime > 500) {
      let disTime = endTime - startTime
      window.$bs.tagParams.api_info.push(
        {
          name: url,
          start_time: startTime,
          end_time: endTime,
          dis_time: disTime
        }
      )
    }
    return data
  },
  async post (url, params, opt) {
    let startTime = new Date().getTime()
    let welikeToken = utils.cookie.get('welikeToken') || ''
    let commonParams = ''
    if (welikeToken) {
      commonParams = `source=web&token=${welikeToken}&appType=4`
    } else {
      commonParams = `source=web&appType=4`
    }
    const options = Object.assign({
      withCredentials: true,
      params: commonParams
    }, opt)
    let { data } = await axios.post(`${url}${commonParams}`, params, options).catch((error) => {
      return error.response
    })
    let endTime = new Date().getTime()
    if (endTime - startTime > 500) {
      let disTime = endTime - startTime
      window.$bs.tagParams.api_info.push(
        {
          name: url,
          start_time: startTime,
          end_time: endTime,
          dis_time: disTime
        }
      )
    }
    return data
  },
  async put (url, params, opt) {
    let startTime = new Date().getTime()
    let welikeToken = utils.cookie.get('welikeToken') || ''
    let commonParams = ''
    if (welikeToken) {
      commonParams = `source=web&token=${welikeToken}&appType=4`
    } else {
      commonParams = `source=web&appType=4`
    }
    let { data } = await axios.put(`${url}${commonParams}`, commonParams, { withCredentials: true }).catch((error) => {
      return error.response
    })
    let endTime = new Date().getTime()
    if (endTime - startTime > 500) {
      let disTime = endTime - startTime
      window.$bs.tagParams.api_info.push(
        {
          name: url,
          start_time: startTime,
          end_time: endTime,
          dis_time: disTime
        }
      )
    }
    return data
  }
}
